import fs from "fs-extra";
import moment from "moment";
import path from "path";
import { BaseTask, TaskResult } from "../../common/tasks/BastTask.js";
import { toolchain } from "../../toolchain.js";
import { UploadResult } from "../../tools/WechatTools.js";
import { WebGLEnv } from "../WebGLEnv.js";
import { CheckEnvTask } from "../../common/tasks/CheckEnvTask.js";
import { Nullable } from "../../typings.js";
import { default as tmg } from 'tt-minigame-ide-cli';
import { env } from "../../env.js";
import { MsgSupporter, sendBuildFailureAlert, sendRobotImage, sendRobotMsg } from "../../tools/alert.js";
import { Hudson } from "../../tools/hudson.js";

export interface WebGLDouyinUploadData {
    success: boolean
    result: { qrcodeFile: string }
}

export class WebGLDouyinUploadTask extends BaseTask<WebGLDouyinUploadData> {
    async run(): Promise<TaskResult<WebGLDouyinUploadData>> {
        // https://developer.open-douyin.com/docs/resource/zh-CN/mini-game/develop/dev-tools/developer-instrument/development-assistance/ide-cli#637a3aa1

        const exportRoot = path.join(toolchain.params.workSpacePath, WebGLEnv.ExportDouyinRoot);
        await tmg.loginByEmail({
            email: env.ttMail,
            password: env.ttPswd
        }).catch((reason) => {
            console.error('login failed:', reason);
            sendBuildFailureAlert('抖音登录失败，请尝试手动上传');
            process.exit(1);
        });
        
        // 上传
        // 读取版本号，注意不能直接读取project目录下的版本号，因可能本次上传任务是由于上次构建自动上传失败后手动发起的，而这过程中可能构建过其他版本
        // 应该从export目录底下的版本号记录文件读取版本号
        const appVerFile = path.join(toolchain.params.workSpacePath, WebGLEnv.DouyinAppVerFile);
        const version = await fs.readFile(appVerFile, 'utf-8');
        // 记录本次版本号
        toolchain.unity.commitFullBuildVer(version);
        
        const publishDesc = this.cmdOption.uploadMinigameDesc + '@' + moment().format(moment.HTML5_FMT.DATETIME_LOCAL);
        const output = path.join(exportRoot, `${version}.png`);

        const res = await tmg.unity.upload({
            projectPath: toolchain.params.workSpacePath,
            output,
            version,
            publishDesc,
            channel: '1',
            bgColor: '#ffffffff'
        }).catch((reason) => {
            console.error('upload failed:', reason);
            sendBuildFailureAlert('抖音上传失败，请尝试手动上传');
            process.exit(1);
        });
        console.log('upload result: ', res);

        let qrcodeFile = '';
        if (fs.existsSync(output)) {
            // 拷贝到res目录
            await fs.copyFile(output, path.join(toolchain.params.uploadPath, `${toolchain.params.channelCfg.gameid}_douyin.png`));
            // 发送二维码到群里
            qrcodeFile = output;
            if (MsgSupporter != 'douyin') {
                // 抖音直接把二维码嵌入消息卡片中
                const obuff = await fs.readFile(output);
                await sendRobotMsg('text', `扫码体验${Hudson.getJobName()} 抖音 ${version}`);
                await sendRobotImage('data:image/png;base64,' + obuff.toString('base64'));
            }
        }

        return { success: true, errorCode: 0, data: { success: true, result: { qrcodeFile } } };
    }

    get dependencies(): Nullable<string[]> {
        return [CheckEnvTask.name]
    }
}
